#include "usocket.h"
#include "../util/lock.h"

usocket::usocket()
{
	m_socket = 0;
}

usocket::~usocket()
{
  if(m_socket != 0)
	  close(m_socket);
}
	
bool usocket::init(uint16 d_port)
{
	func_lock s_lock;
	sockaddr_in  usersocket;
	int          value;
	socklen_t    tempsize;
	uint32       errorcode = 0;

	m_socket = socket(PF_INET, SOCK_DGRAM, 0);


	if ( m_socket == -1)
		return false;

	usersocket.sin_family = AF_INET;
	usersocket.sin_port   = htons(d_port);
	usersocket.sin_addr.s_addr = INADDR_ANY;
	
	value = bind(m_socket, (sockaddr*)(&usersocket),
		   sizeof(sockaddr_in));

	if( value == -1)
	{
		close(m_socket);
		return false;
	}
		
		
	tempsize = sizeof(sockaddr_in);
	value = getsockname(m_socket,(sockaddr*)(&usersocket),&tempsize);
	return true;
}

bool usocket::sendbuf(uint32 ip, uint16 port, char* buf, uint16 buf_size)
{
	func_lock s_lock;
	sockaddr_in       touser;
	memset(&touser, 0, sizeof(touser));
	touser.sin_family = AF_INET;
	touser.sin_port   = htons(port);
	touser.sin_addr.s_addr = ip;
		
	return sendto(m_socket, buf, buf_size, 0,
			(sockaddr*)(&touser), sizeof(sockaddr)) != -1;
}

bool usocket::recvbuf(uint32* ip, uint16* port, char* buf, uint16* buf_size)
{
	func_lock s_lock;
	socklen_t bufsize = 1500;
	int value;
	sockaddr_in r_socket;
	
	value = recvfrom(m_socket, buf,bufsize, 0,
		(sockaddr*)(&r_socket), &bufsize);

	*buf_size = value;

	if( value == -1)
	    return false;

	*ip   = r_socket.sin_addr.s_addr;
	*port = ntohs(r_socket.sin_port);
	return true;

}

